package com.situ.dao;

import com.situ.entity.Role;
import com.situ.util.DBUtil;
import com.situ.vo.RoleVO;

import java.util.ArrayList;
import java.util.List;

public class RoleDao {

    public List<Role> select(String name, Integer page, Integer limit) {
        List<Object> params = new ArrayList<>();
        String sql = "select * from role ";
        sql += concat(name, params);
        sql += " limit ?,?";
        params.add((page - 1) * limit);
        params.add(limit);
        return DBUtil.executeDQL(sql, Role.class, params.toArray());
    }

    private String concat(String name, List<Object> params) {
        String result = "";
        if (name != null && !name.isEmpty()) {
            result = " where instr(name,?)>0 ";
            params.add(name);
        }
        return result;
    }

    //新增用户
    public int insert(Role role) {
        return DBUtil.executeDML("insert into role(name) values(?)", role.getName());
    }

    public int delete(Integer id) {
        return DBUtil.executeDML("delete from role where id = ?", id);
    }

    public int update(Role role) {
        return DBUtil.executeDML("update role set name=? where id=?", role.getName(), role.getId());
    }

    public Long count(String name) {
        List<Object> params = new ArrayList<>();
        return DBUtil.executeCount("select count(1) from role " + concat(name, params), params.toArray());
    }

    public List<Role> info(Integer id) {
        return DBUtil.executeDQL("select * from role where id = ?", Role.class, id);
    }

    public List<RoleVO> all(Integer uid) {
        return DBUtil.executeDQL("select role.id,role.name,user_role.id as 'checked' from role left join user_role on role.id = user_role.role_id and user_role.user_id=?", RoleVO.class, uid);
    }
}
